<template>
  <div class="literature-detail-page">
    <div class="literature-container">
      <!-- 文献头部 -->
      <div class="literature-header">
        <h1 class="literature-title">{{ literatureInfo.title }}</h1>
        <div class="literature-meta-info">
          <span class="meta-item" v-if="literatureInfo.authors">
            <i class="fas fa-user"></i>
            {{ literatureInfo.authors }}
          </span>
          <span class="meta-item" v-if="literatureInfo.subjects">
            <i class="fas fa-tag"></i>
            {{ literatureInfo.subjects }}
          </span>
          <span class="meta-item">
            <i class="fas fa-eye"></i>
            {{ literatureInfo.viewCount || 0 }} 次阅读
          </span>
          <span class="meta-item">
            <i class="fas fa-heart"></i>
            {{ literatureInfo.likeCount || 0 }} 点赞
          </span>
          <span class="meta-item">
            <i class="fas fa-comment-alt"></i>
            {{ literatureInfo.commentCount || 0 }} 条评论
          </span>
        </div>
      </div>

      <!-- 外网链接区域 -->
      <div class="link-section" v-if="literatureInfo.pdfLink">
        <div class="link-card">
          <div class="link-info">
            <i class="fas fa-external-link-alt link-icon"></i>
            <div class="link-text">
              <h3 class="link-title">查看完整文献</h3>
              <p class="link-desc">点击下方按钮在新窗口中打开文献链接</p>
            </div>
          </div>
          <a
            :href="literatureInfo.pdfLink"
            target="_blank"
            rel="noopener noreferrer"
            class="link-button"
          >
            <i class="fas fa-file-pdf"></i>
            打开文献链接
          </a>
        </div>
      </div>

      <!-- 互动按钮区域 -->
      <div class="literature-actions">
        <button
          class="action-btn like-btn"
          :class="{ liked: literatureInfo.isLike === 0 }"
          @click="toggleLike"
        >
          <i class="fas fa-heart"></i>
          <span>{{ literatureInfo.isLike === 0 ? '已点赞' : '点赞' }}</span>
          <span class="count">{{ literatureInfo.likeCount || 0 }}</span>
        </button>
      </div>

      <!-- 评论区域 -->
      <div class="comments-section">
        <h3 class="section-title">
          <span>评论 ({{ literatureInfo.commentCount || 0 }})</span>
        </h3>

        <!-- 评论输入框 -->
        <div class="comment-input-area">
          <n-input
            class="comment-input"
            v-model:value="newComment"
            placeholder="写下你的评论..."
            maxlength="100"
          >
            <template #suffix>
              <n-button @click="addComment" tertiary circle type="primary">
                <template #icon>
                  <n-icon><IosSend /></n-icon>
                </template>
              </n-button>
            </template>
          </n-input>
        </div>

        <!-- 评论列表 -->
        <div class="comment-list">
          <div class="comment-item" v-for="comment in comments" :key="comment.id">
            <n-avatar class="avatar" :src="comment?.user?.avatar" round />
            <div class="comment-content">
              <div class="comment-header">
                <span class="comment-author">{{ comment?.user?.username }}</span>
                <span class="badge author-badge" v-if="comment.isAuthor">作者</span>
                <span class="badge user-badge" v-if="comment.isLoginUser">我</span>
                <span class="comment-time">{{ comment.createTime }}</span>
              </div>
              <p class="comment-text">{{ comment.content }}</p>
            </div>
          </div>

          <!-- 空状态提示 -->
          <div v-if="!comloading && comments.length === 0" class="comment-tip"> 暂无评论 </div>

          <!-- 加载状态 -->
          <div v-if="comloading" class="comment-tip"> 加载中... </div>

          <!-- 没有更多数据提示 -->
          <div v-if="!comloading && isLastPage && comments.length > 0" class="comment-tip">
            暂无更多
          </div>
          <div
            v-if="!comloading && comments.length !== 0 && !isLastPage"
            class="load-more"
            @click="loadMoreComments"
          >
            <span>点击加载更多评论</span>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script lang="ts" setup>
  import { ref, onMounted, watch } from 'vue';
  import { useRoute } from 'vue-router';
  import { getCommentListApi, addCommonApi, likeChapterApi } from '@/api/course';
  import { getLiteratureListApi } from '@/api/literature/index';
  import { IosSend } from '@vicons/ionicons4';
  import { ResultEnum } from '@/enums/httpEnum';
  import { useMessage } from 'naive-ui';
  import { useUserStore } from '@/store/modules/user';

  const route = useRoute();
  const message = useMessage();
  const userStore = useUserStore();

  const literatureId = ref('');
  const literatureInfo = ref<any>({
    id: '',
    title: '',
    authors: '',
    subjects: '',
    pdfLink: '',
    viewCount: 0,
    likeCount: 0,
    commentCount: 0,
    isLike: 1, // 1-未点赞，0-已点赞
  });

  // 评论相关
  const newComment = ref('');
  const comments = ref<any[]>([]);
  const pageNum = ref(1);
  const pageSize = 10;
  const comloading = ref(false);
  const isLastPage = ref(false);
  const pages = ref(0);

  // 监听路由变化
  watch(
    () => route.query,
    async (newParams: any) => {
      if (newParams.id) {
        literatureId.value = newParams.id;
        await getLiteratureDetail();
        await getCommonList(true);
      }
    },
    { immediate: true }
  );

  // 获取文献详情
  async function getLiteratureDetail() {
    try {
      // 尝试通过 id 查询，如果 API 不支持，可能需要通过其他字段查询
      const params: any = {
        pageNum: 1,
        pageSize: 100, // 增加页面大小，确保能找到目标文献
      };

      // 如果路由中有 id，尝试通过 id 查询
      if (literatureId.value) {
        params.id = literatureId.value;
      }

      const data: any = await getLiteratureListApi(params);
      const records: any[] = data.records || [];
      
      // 如果传入了 id，尝试在结果中查找匹配的文献
      let paper: any = null;
      if (literatureId.value) {
        paper = records.find((p: any) => p.id === literatureId.value || p.arxivId === literatureId.value);
      }
      
      // 如果没找到，使用第一条记录（作为备用方案）
      if (!paper && records.length > 0) {
        paper = records[0];
      }

      if (paper) {
        literatureInfo.value = {
          id: paper.id || paper.arxivId || literatureId.value,
          title: paper.title || '未知标题',
          authors: paper.authors || '未知作者',
          subjects: paper.subjects || '未知学科',
          pdfLink: paper.pdfLink || paper.link || '',
          viewCount: paper.viewCount || 0,
          likeCount: paper.likeCount || 0,
          commentCount: paper.commentCount || 0,
          isLike: paper.isLike !== undefined ? paper.isLike : 1,
        };
      } else {
        message.warning('未找到该文献信息');
      }
    } catch (error) {
      console.error('获取文献详情失败:', error);
      message.error('获取文献详情失败，请稍后重试');
    }
  }

  // 获取评论列表
  async function getCommonList(isRefresh = false) {
    if (comloading.value || (isLastPage.value && !isRefresh)) return;

    comloading.value = true;
    try {
      const params = {
        pageNum: pageNum.value,
        pageSize: pageSize,
        bizType: 2, // 2-文献，1-文章，0-视频章节
        bizId: literatureId.value,
      };

      const data: any = await getCommentListApi(params);

      let list = data.records || [];
      if (isRefresh) {
        comments.value = list;
        pageNum.value = 1;
        isLastPage.value = false;
      } else {
        comments.value = [...comments.value, ...list];
      }

      pages.value = data.pages;

      if (list.length < pageSize) {
        isLastPage.value = true;
      } else {
        pageNum.value++;
      }
    } catch (error) {
      console.error('error:', error);
    } finally {
      comloading.value = false;
    }
  }

  // 添加评论
  const addComment = async () => {
    if (!newComment.value.trim()) {
      message.warning('请输入评论内容');
      return;
    }

    try {
      const params = {
        content: newComment.value,
        bizType: 2, // 2-文献，1-文章，0-视频章节
        bizId: literatureId.value,
      };

      const { code, data } = await addCommonApi(params);
      if (code == ResultEnum.SUCCESS) {
        comments.value.unshift({
          id: data,
          createTime: '刚刚',
          likeCount: 0,
          isLike: false,
          isAuthor: false,
          isLoginUser: true,
          user: {
            username: userStore?.info?.username,
            avatar: userStore?.info?.avatar,
          },
          ...params,
        });

        literatureInfo.value.commentCount++;
        message.success('评论发表成功');
      } else {
        message.error('发表评论失败，请稍后重试！');
      }
    } catch (error) {
      message.error('发表评论失败，请稍后重试！');
    }

    newComment.value = '';
  };

  // 加载更多评论
  const loadMoreComments = () => {
    getCommonList();
  };

  // 点赞功能
  const toggleLike = async () => {
    try {
      const params = {
        bizType: 2, // 2-文献，1-文章，0-视频章节
        bizId: literatureId.value,
      };

      const { code, data } = await likeChapterApi(params);
      if (code == ResultEnum.SUCCESS) {
        if (data) {
          // 已点赞，取消点赞
          literatureInfo.value.isLike = 1;
          literatureInfo.value.likeCount = Math.max(0, (literatureInfo.value.likeCount || 0) - 1);
        } else {
          // 未点赞，点赞
          literatureInfo.value.isLike = 0;
          literatureInfo.value.likeCount = (literatureInfo.value.likeCount || 0) + 1;
        }
      } else {
        message.error('点赞失败，请稍后重试！');
      }
    } catch (error) {
      message.error('点赞失败，请稍后重试！');
    }
  };

  onMounted(() => {
    if (route.query.id) {
      literatureId.value = route.query.id as string;
      getLiteratureDetail();
      getCommonList(true);
    }
  });
</script>

<style scoped>
  .literature-detail-page {
    max-width: 1200px;
    margin: 0 auto;
    padding: 20px;
  }

  .literature-container {
    background: white;
    border-radius: 12px;
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
    padding: 40px;
  }

  /* 文献头部 */
  .literature-header {
    margin-bottom: 30px;
    padding-bottom: 20px;
    border-bottom: 1px solid #eee;
  }

  .literature-title {
    font-size: 32px;
    font-weight: 700;
    color: #2c3e50;
    margin-bottom: 20px;
    line-height: 1.4;
  }

  .literature-meta-info {
    display: flex;
    flex-wrap: wrap;
    gap: 20px;
    color: #666;
    font-size: 14px;
  }

  .meta-item {
    display: flex;
    align-items: center;
    gap: 6px;
  }

  .meta-item i {
    color: #999;
  }

  /* 外网链接区域 */
  .link-section {
    margin-bottom: 30px;
    padding-bottom: 30px;
    border-bottom: 1px solid #eee;
  }

  .link-card {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 24px;
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    border-radius: 12px;
    color: white;
  }

  .link-info {
    display: flex;
    align-items: center;
    gap: 16px;
    flex: 1;
  }

  .link-icon {
    font-size: 32px;
    opacity: 0.9;
  }

  .link-text {
    flex: 1;
  }

  .link-title {
    font-size: 20px;
    font-weight: 600;
    margin: 0 0 8px 0;
    color: white;
  }

  .link-desc {
    font-size: 14px;
    margin: 0;
    opacity: 0.9;
    color: white;
  }

  .link-button {
    display: flex;
    align-items: center;
    gap: 8px;
    padding: 12px 24px;
    background: white;
    color: #667eea;
    border-radius: 8px;
    font-weight: 600;
    text-decoration: none;
    transition: all 0.3s ease;
    white-space: nowrap;
  }

  .link-button:hover {
    transform: translateY(-2px);
    box-shadow: 0 8px 20px rgba(0, 0, 0, 0.2);
    background: #f8f9fa;
  }

  .link-button i {
    font-size: 18px;
  }

  /* 互动按钮区域 */
  .literature-actions {
    display: flex;
    gap: 20px;
    padding: 20px 0;
    margin-bottom: 30px;
    border-bottom: 1px solid #eee;
  }

  .action-btn {
    display: flex;
    align-items: center;
    gap: 8px;
    background: none;
    border: 1px solid #e2e8f0;
    border-radius: 8px;
    cursor: pointer;
    font-size: 16px;
    color: #555;
    transition: all 0.3s ease;
    padding: 10px 20px;
  }

  .action-btn:hover {
    background: #f5f7fa;
    border-color: #cbd5e0;
  }

  .like-btn.liked {
    color: #ff4d4f;
    border-color: #ff4d4f;
    background: #fff1f0;
  }

  .like-btn.liked i {
    animation: pulse 0.5s;
  }

  .action-btn i {
    font-size: 18px;
  }

  .action-btn .count {
    font-weight: 600;
  }

  @keyframes pulse {
    0% {
      transform: scale(1);
    }
    50% {
      transform: scale(1.3);
    }
    100% {
      transform: scale(1);
    }
  }

  /* 评论区域 */
  .comments-section {
    margin-top: 30px;
  }

  .section-title {
    font-size: 20px;
    font-weight: 600;
    margin-bottom: 20px;
    color: #2c3e50;
  }

  .comment-input-area {
    margin-bottom: 30px;
  }

  .comment-input {
    padding: 10px 0;
  }

  .comment-list {
    display: flex;
    flex-direction: column;
    gap: 20px;
  }

  .comment-item {
    display: flex;
    gap: 15px;
    background: #f9fbfd;
    border: 1px solid #eef2f7;
    padding: 20px;
    border-radius: 8px;
  }

  .avatar {
    width: 40px;
    height: 40px;
    flex-shrink: 0;
  }

  .comment-content {
    flex: 1;
  }

  .comment-header {
    display: flex;
    align-items: center;
    gap: 10px;
    margin-bottom: 8px;
  }

  .comment-author {
    font-weight: 600;
    color: #2c3e50;
  }

  .badge {
    font-size: 12px;
    padding: 2px 6px;
    border-radius: 3px;
  }

  .author-badge {
    background: #fff7e6;
    color: #fa8c16;
  }

  .user-badge {
    background: #e6f7ff;
    color: #1890ff;
  }

  .comment-time {
    color: #999;
    font-size: 13px;
    margin-left: auto;
  }

  .comment-text {
    margin: 0;
    line-height: 1.6;
    color: #333;
  }

  .comment-tip {
    text-align: center;
    height: 60px;
    line-height: 60px;
    color: #999;
    font-size: 16px;
  }

  .load-more {
    text-align: center;
    color: #1890ff;
    padding: 15px;
    cursor: pointer;
    font-weight: 500;
    margin-top: 10px;
    border-radius: 8px;
    transition: background 0.3s;
  }

  .load-more:hover {
    background: #f0f7ff;
  }

  /* 响应式设计 */
  @media (max-width: 768px) {
    .literature-detail-page {
      padding: 10px;
    }

    .literature-container {
      padding: 20px;
    }

    .literature-title {
      font-size: 24px;
    }

    .literature-meta-info {
      gap: 15px;
      font-size: 12px;
    }

    .link-card {
      flex-direction: column;
      gap: 20px;
    }

    .link-button {
      width: 100%;
      justify-content: center;
    }

    .literature-actions {
      flex-direction: column;
      gap: 10px;
    }

    .action-btn {
      width: 100%;
      justify-content: center;
    }
  }
</style>